package controller

import (
	"context"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/devicec"
	"sale-admin/internal/app/web/service/robotinfo"
	"sale-admin/internal/dal"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type RobotInfo struct{}

// 设置机器商品排序
func (r RobotInfo) SetRobotSort(c *gin.Context) {
	var params struct {
		SalesID string `json:"sales_id"`
		GoodsID string `json:"goods_id"`
		Multi   int    `json:"multi"`
		Sort    int    `json:"sort"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	db := mysql.NewDB()
	err := robotinfo.RobotInfoService{}.SetRobotSort(c.Request.Context(), db, params.SalesID, params.GoodsID, params.Multi, params.Sort)
	response.JSON(c, nil, err)
}

/**
 *
 * 查询机器已售出和库存信息 --- 按照库存大小排序
 */
func (r RobotInfo) GetRobotShopInfo(c *gin.Context) {
	var params struct {
		Page    int    `json:"page"`
		Limit   int    `json:"limit"`
		SalesID string `json:"sales_id"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	db := mysql.NewDB()

	// 获取机器的库存及商品剩余库存信息
	data, count, err := robotinfo.RobotInfoService{}.GetInventoryBySalesid(c.Request.Context(), db, merchantID, params.SalesID, params.Page, params.Limit)

	for k, v := range data {
		data[k].ErrorContainerNum, data[k].ZeroContainerNum, _ = robotinfo.RobotInfoService{}.GetHistoryErrorContainerNums(context.Background(), dal.Q, v.SalesID)
		var data2 []robotinfo.MaRobotSalesInfoDetail
		for _, v1 := range v.Data {
			if (v1.RobotGoodsInventory == 0 && v1.GoodsMaxInventory == 0) || v1.ContainerStatus == 0 {
				// 删除已下架的商品
			} else {
				data2 = append(data2, v1)
			}
		}
		data[k].Areas3 = v.Data[0].Areas3
		if len(data2) > 0 {
			data[k].Data = data2
		}
	}
	response.JSON(c, gin.H{
		"count":                 count,
		"robot_goods_inventory": data,
	}, err)

}

/**
 *
 * 历史库存之Group日期、机器
 */
func (r RobotInfo) GetHistoryInventoryOfGoods(c *gin.Context) {
	var params struct {
		SalesID   string `json:"sales_id"`
		StartTime string `json:"start_time"`
		EndTime   string `json:"end_time"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")

	// 获取机器的库存及商品剩余库存信息
	db := mysql.NewDB()
	data, err := robotinfo.RobotInfoService{}.HistoryInventoryOfGoods(c.Request.Context(), db, merchantID,
		params.SalesID, params.StartTime, params.EndTime)
	response.JSON(c, gin.H{
		"data": data,
	}, err)
}

/**
 *
 * 历史库存之Group日期、机器
 */
func (r RobotInfo) GetHistoryRobotShopInfo(c *gin.Context) {
	var params struct {
		Page      int    `json:"page"`
		Limit     int    `json:"limit"`
		SalesID   string `json:"sales_id"`
		StartTime string `json:"start_time"`
		EndTime   string `json:"end_time"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")

	// 获取机器的库存及商品剩余库存信息
	db := mysql.NewDB()
	data, count, err := robotinfo.RobotInfoService{}.HistoryInventoryBySalesid(c.Request.Context(), db, merchantID,
		params.SalesID, params.StartTime, params.EndTime, params.Page, params.Limit)
	for k, v := range data {
		// grpc 获取设备的楼层
		req := &devicec.DeviceDetailReq{}
		req.IdentificationCode = v.SalesID
		deviceClient, clientErr := client.GetDeviceAdminClient()
		if clientErr != nil {
			logx.Error(context.Background(), "grpc device client error", logx.Err(clientErr))
			return
		}
		res, _ := deviceClient.DeviceDetail(context.Background(), req)
		if res.Device.Floor != "" {
			v.Floor = res.Device.Floor
		} else {
			v.Floor = "未设置"
		}
		data[k] = v
	}
	response.JSON(c, gin.H{
		"count": count,
		"data":  data,
	}, err)

}

/**
 *
 * 空货数据详情
 */
func (r RobotInfo) GetZeroStockDataDetail(c *gin.Context) {
	var params struct {
		StockType int    `json:"stock_type"` // 1单日空货、2连续空货
		StartTime string `json:"start_time"` // 开始时间
		EndTime   string `json:"end_time"`   // 结束时间
		RobotName string `json:"robot_name"` // 机器名称
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")

	db := mysql.NewDB()
	data, err := robotinfo.RobotInfoService{}.GetZeroStockDataDetail(c.Request.Context(), db, merchantID, params.StockType,
		params.StartTime, params.EndTime, params.RobotName)

	response.JSON(c, gin.H{
		"data": data,
	}, err)
}

// 空货数据
func (r RobotInfo) GetZeroStockData(c *gin.Context) {
	var params struct {
		StockType int    `json:"stock_type"` // 1单日空货、2连续空货
		StartTime string `json:"start_time"`
		EndTime   string `json:"end_time"`
		Page      int    `json:"page"`
		Limit     int    `json:"limit"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	db := mysql.NewDB()

	data, count, err := robotinfo.RobotInfoService{}.GetZeroStockData(c.Request.Context(), db, merchantID,
		params.StockType, params.StartTime, params.EndTime, params.Page, params.Limit)

	response.JSON(c, gin.H{
		"data":  data,
		"count": count,
	}, err)
}

// RobotSaleInfoLog 获取补货记录
func (r RobotInfo) RobotSaleInfoLog(c *gin.Context) {
	var params struct {
		SalesID    string `json:"sales_id"`
		ProvinceID string `json:"province_id"`
		CityID     string `json:"city_id"`
		DistrictID string `json:"district_id"`
		LocationID string `json:"location_id"`
		StartTime  string `json:"start_time"`
		EndTime    string `json:"end_time"`
		Type       int    `json:"type"`
		Page       int    `json:"page"`
		Limit      int    `json:"limit"`
		Username   string `json:"username"`
	}

	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	data, count, err := robotinfo.RobotInfoService{}.RobotSaleInfoLog(
		c.Request.Context(),
		params.SalesID,
		params.ProvinceID, params.CityID, params.DistrictID, params.LocationID,
		params.StartTime, params.EndTime,
		params.Type, params.Page, params.Limit,
		params.Username,
	)
	response.JSON(c, gin.H{
		"data":  data,
		"count": count,
	}, err)
}

// 获取补货商品变动详情
func (r RobotInfo) RobotSaleInfoLogDetail(c *gin.Context) {
	var params struct {
		LogID int64 `json:"log_id"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误！", -1))
		return
	}
	// 返回数据和查询结果的总数
	data, count, err := robotinfo.RobotInfoService{}.LogDetail(c.Request.Context(), dal.Q, params.LogID)
	response.JSON(c, gin.H{
		"data":  data,
		"count": count,
	}, err)
}
